import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import javax.swing.filechooser.FileSystemView;

import com.sun.org.apache.xerces.internal.util.URI;
import com.sun.org.apache.xml.internal.resolver.helpers.FileURL;

import sun.management.FileSystem;
import sun.management.FileSystemImpl;


public class CorelData 
{
	public static final int TRADING_DAYS_IN_A_YEAR = 257;
	private final double RISK_FREE_RATE = .02;
	
	public double getCorel(String stock1, String stock2) throws Exception
	{
		double[] scores1 = getstockarray(stock1);
		double[] scores2 = getstockarray(stock2);
		
		
		double result = 0;
        double sum_sq_x = 0;
        double sum_sq_y = 0;
        double sum_coproduct = 0;
        double mean_x = scores1[0];
        double mean_y = scores2[0];
        for(int i=1;i<scores1.length;i++){
        	if(scores1[i] == -1 || scores2[i]==-1) {
        		break;
        	}
            double sweep =Double.valueOf(i-1)/i;
            double delta_x = scores1[i-1]-mean_x;
            double delta_y = scores2[i-1]-mean_y;
            sum_sq_x += delta_x * delta_x * sweep;
            sum_sq_y += delta_y * delta_y * sweep;
            sum_coproduct += delta_x * delta_y * sweep;
            mean_x += delta_x / i;
            mean_y += delta_y / i;
        }
        double pop_sd_x = (double) Math.sqrt(sum_sq_x/scores1.length);
        double pop_sd_y = (double) Math.sqrt(sum_sq_y/scores1.length);
        double cov_x_y = sum_coproduct / scores1.length;
        result = cov_x_y / (pop_sd_x*pop_sd_y);
        return result;
	}
	
	public double[] getstockarray(String symbol) throws Exception
	{
		double[] scores = new double[1000];
		URLConnection connection = null;
		InputStream in = null;
		
		File stockData = new File(MainScreen.dataDirectory.getAbsolutePath()+ "\\tempdata.csv");
		if (stockData.exists()) {
			stockData.delete();
		}
		//System.out.println(stockData.getAbsolutePath());
		stockData.createNewFile();
		OutputStream out = new BufferedOutputStream(new FileOutputStream(stockData));
		URL url = new URL("http://www.google.com/finance/historical?q="+symbol+"&startdate=Oct%2023,%202003&enddate=Feb+10,+2009&output=csv");
		connection = url.openConnection();
		in = connection.getInputStream();
		byte[] buffer = new byte[1024];
		int numRead;
		long numWritten = 0;
		while((numRead = in.read(buffer)) != -1)
		{
			out.write(buffer, 0, numRead);
			numWritten += numRead;
		}
		out.close();
		
		CSVReader reader = new CSVReader(new FileReader(stockData));
		reader.readNext();
		String [] nextLine;
		int pointer = 0;
	    while ((nextLine = reader.readNext()) != null && pointer < 1000) {
	    	// nextLine[] is an array of values from the line
	        //System.out.println("[1] = " + nextLine[1] +" [2] = " + nextLine[2]+" [3] = " + nextLine[3] + " pointer = " + pointer);
	        scores[pointer] = Double.parseDouble(nextLine[4]);
	        pointer++;
	    }
	    while(pointer<1000) {
	    	scores[pointer] = -1;
	    	pointer++;
	    }
		
		
		return scores;
	}

	public void getHistoricalData(String symbol) {
		// TODO Auto-generated method stub
		URLConnection connection = null;
		InputStream in = null;
		
		File histData = new File(MainScreen.dataDirectory.getAbsolutePath()+ "\\" + symbol + ".csv");
		if (histData.exists()) {
			histData.delete();
		}
		System.out.println(histData.getAbsolutePath());
		try {
		histData.createNewFile();
		OutputStream out = new BufferedOutputStream(new FileOutputStream(histData));
		URL url = new URL("http://www.google.com/finance/historical?q="+symbol+"&startdate=Oct%2023,%202003&enddate=Feb+10,+2009&output=csv");
		connection = url.openConnection();
		in = connection.getInputStream();
		byte[] buffer = new byte[1024];
		int numRead;
		long numWritten = 0;
		while((numRead = in.read(buffer)) != -1)
		{
			out.write(buffer, 0, numRead);
			numWritten += numRead;
		}
		out.close();
		}
		catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public double getSharpeRatio (String stock1) throws Exception {
			double[] closingPrices = getstockarray(stock1);
			double result = 0.0;
		
			if(closingPrices.length < TRADING_DAYS_IN_A_YEAR*2) {
				return -1;
			}
			double xSqrdSum = 0.0;
			double xSum = 0.0;
			double r = 0.0;
			for (int i =0;i<TRADING_DAYS_IN_A_YEAR;i++ ) {
				if(closingPrices[i+TRADING_DAYS_IN_A_YEAR] == -1) {
					return -1;
				}
				r=(closingPrices[i]-closingPrices[i+TRADING_DAYS_IN_A_YEAR])/closingPrices[i+TRADING_DAYS_IN_A_YEAR];
				xSqrdSum += r*r;
				xSum += r;
			}
			return ((closingPrices[0]-closingPrices[TRADING_DAYS_IN_A_YEAR])/closingPrices[TRADING_DAYS_IN_A_YEAR]-RISK_FREE_RATE)/Math.sqrt((xSqrdSum-xSum)/TRADING_DAYS_IN_A_YEAR);
	}
	
}
